package service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.DailyRollingFileAppender;

import dao.BaseDao;
import dao.StaffDao;
import vo.RoleUser;
import vo.Staff;

public class StaffServiceImpl implements StaffService{
	StaffDao dao;
	@Override
	public Staff getStaffByNo(int staffNo) {
		List list = new ArrayList();
		String hql = "from Staff where staffNo='"+staffNo+"'";
		list = dao.select(hql);
		Staff staff = (Staff)list.get(0);
		return staff;
	}
	
	@Override
	public String addStaff(Staff staff,String role) {
		Date date = new Date();
		Timestamp employedDate = new Timestamp(date.getTime());
		staff.setEmployedDate(employedDate);
		staff.setLocked("false");
		String hql = "from Staff where staffNo='"+staff.getStaffNo()+"'";
		if(dao.select(hql).size()>0){
			return "员工编号已存在";
		}else{
			if(dao.save(staff)){
				dao.addRoles(staff,role);
				return "增加成功";
			}else{
				return "增加失败";
			}
		}
	}
	
	@Override
	public String updateStaff(Staff staff) {
		System.out.println(staff.toString());
		if(dao.updateBySql(staff)){
			return "修改成功";
		}else{
			return "修改失败";
		}
	}
	
	@Override
	public String deleteStaff(Staff staff) {		
		if(dao.deleteByNo(staff.getStaffNo())){
			return "删除成功";
		}else{
			return "删除失败";
		}
	}
	
	@Override
	public String findStaff(String key) {
		String hql = "from Staff where staffNo='"+key+"'";
		List<Staff> list = new ArrayList<Staff>();
		list = dao.select(hql);
		return list.get(0).getName();
	}
	
	@Override
	public List<Staff> findAllStaff() {
		List result = new ArrayList();
		List<Staff> list = new ArrayList<Staff>();
		list = dao.findAll();
		for(Staff staff:list){
			Map<String ,Object> map = new HashMap<String, Object>();
			if(staff.getLocked().equals("false")){
				map.put("staff",staff);
				String role = dao.getRole(staff);
				if(role.equals("2")){
					map.put("role", "staff");
				}else if(role.equals("1")){
					map.put("role", "admin");
				}
				result.add(map);
			}		
		}
		return result;
	}

	public StaffDao getDao() {
		return dao;
	}

	public void setDao(StaffDao dao) {
		this.dao = dao;
	}
	
}
